//
//  NativeVapView.swift
//  vap_plugin
//
//  Created by sunc on 2024/5/28.
//

import Foundation
import UIKit
import Flutter

class NativeVapView :NSObject, FlutterPlatformView,HWDMP4PlayDelegate, VAPWrapViewDelegate{
    
    
    var flutterResult : FlutterResult?
    
    var vapView : QGVAPWrapView?
    var mainView : UIView?
    
    var arguments : Dictionary<String, Any>?
    
    func view() -> UIView {
        return mainView ?? UIView()
    }
    
    init(withFrame frame: CGRect,viewID: Int64,args :Any?,messenger :FlutterBinaryMessenger) {
        super.init()
        if(vapView == nil){
            mainView = UIView(frame: UIScreen.main.bounds)
            vapView = QGVAPWrapView.init(frame: mainView!.frame)
            vapView?.hwd_enterBackgroundOP = HWDMP4EBOperationType.stop
            vapView?.isUserInteractionEnabled = true
            vapView?.contentMode = QGVAPWrapViewContentMode.aspectFill
            vapView?.autoDestoryAfterFinish = true
            vapView?.enableOldVersion(true)
        }
        
        let methodChannel = FlutterMethodChannel(name: "com.vap_plugin.ultra.FlutterView_\(viewID)", binaryMessenger: messenger)
        
        
        methodChannel.setMethodCallHandler { [self](call, result) in
            self.initResult(result:result)
            self.mainView?.addSubview(self.vapView!)
            
            let method:String = call.method
            
            switch (method) {
                
            case "playPath":
                if let dict = call.arguments as? Dictionary<String, Any> {
                    configData(dict: dict)
                    let mp4Path:String = dict["path"] as? String ?? ""
                    if mp4Path.count > 0 {
                        self.playByPath(path: mp4Path)
                    }
                }
                break
                
            case "playAsset":
                if let dict = call.arguments as? Dictionary<String, Any> {
                    configData(dict: dict)
                    let asset:String = dict["path"] as? String ?? ""
                    if asset.count > 0 {
                        self.playByAsset(asset: asset)
                    }
                }
                break

            case "pausePlay":
                self.vapView?.pauseHWDMP4()
                break
                
            case "resumePlay":
                self.vapView?.resumeHWDMP4()
                break
                
            case "stopPlay":
                self.vapView?.stopHWDMP4()
                if (self.vapView?.autoDestoryAfterFinish == true) {
                    self.vapView?.removeFromSuperview()
                }
                break
                
            case "manualDestroy":
                self.vapView?.autoDestoryAfterFinish = true
                self.vapView?.stopHWDMP4()
                self.vapView?.removeFromSuperview()
                self.vapView = nil;
                break
                
            default:
                print("无效的method")
            }
        }
    }
    
    func configData(dict :Dictionary<String, Any>) {
        self.arguments = dict
        
        let notDestroy:Bool = ((dict["notDestroy"] as? Bool) ?? false)
        self.vapView?.autoDestoryAfterFinish = !notDestroy
        

        let width = (dict["width"] as? Double) ?? 0
        let height = (dict["height"] as? Double) ?? 0
        if (width > 0 && height > 0) {
            let frame = CGRect(x: 0, y: 0, width: width, height: height)
            self.mainView?.frame = frame
            self.vapView?.frame = frame
        }
    }
    
    func initResult(result: FlutterResult?){
        flutterResult = result
    }
    
    func playByPath(path :String) {
        let repeatCount = (self.arguments?["loopCount"] as? Int) ?? 0
        vapView?.playHWDMP4(path, repeatCount: repeatCount, delegate: self)
    }
    
    func playByAsset(asset :String) {
        let asset2 =  FileManager.shareInstance.handleFlutterSourcePath(assetpath: asset)
        let repeatCount = (self.arguments?["loopCount"] as? Int) ?? 0
        vapView?.playHWDMP4(asset2, repeatCount: repeatCount, delegate: self)
    }
    
    func viewDidStartPlayMP4(_ container: UIView!) {
//        flutterResult?("playStart")
    }
    
    func viewDidPlayMP4(at frame: QGMP4AnimatedImageFrame!, view container: UIView!) {
//        flutterResult?("playDid")
    }
    
    func viewDidStopPlayMP4(_ lastFrameIndex: Int, view container: UIView!) {
//        flutterResult?("playStop")
    }
    
    func viewDidFailPlayMP4(_ error: Error!) {
        flutterResult?(["status":"playFail","msg":error.localizedDescription])
    }
    
    func viewDidFinishPlayMP4(_ totalFrameCount: Int, view container: UIView!) {
        flutterResult?(["status":"playEnd","msg":""])
    }
    
    func vapWrapview_content(forVapTag tag: String, resource info: QGVAPSourceInfo) -> String {
        if (info.type == QGAGAttachmentSourceType.text) {
            if let r =  self.arguments?[tag] as? String {
                return r
            }
        }
     
        return ""
    }
    
    func vapWrapView_loadVapImage(withURL urlStr: String, context: [AnyHashable : Any], completion completionBlock: @escaping VAPImageCompletionBlock) {
        //处理图片替换逻辑
        //context:resource  type=img  contentTag=imgUser
        if let dict = context["resource"] as? QGVAPSourceInfo {
            if (dict.type == QGAGAttachmentSourceType.img) {
                if let data = self.arguments?[dict.contentTag] as? FlutterStandardTypedData {
                  // 处理接收到的二进制数据
                  let binaryData = data.data
                  let image = UIImage(data: binaryData)
                   DispatchQueue.main.async {
                      completionBlock(image, nil, urlStr)
                    }
                }

            }
        }
    }
}
